package com.pro.common.service.file.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

@Slf4j
@Component
public class AdaptiveConcurrencyControl {

    private static final int MIN_CONCURRENCY = 1;
    private static final int MAX_CONCURRENCY = 2;

    private final AtomicInteger current = new AtomicInteger(MIN_CONCURRENCY);

    // 最近 5 分钟内成功/失败计数
    private final LongAdder success = new LongAdder();
    private final LongAdder fail = new LongAdder();

    // 控制升降频率，避免频繁抖动
    private volatile long lastAdjustTime = 0;
    private static final long ADJUST_INTERVAL_MS = 30_000; // 30 秒

    public void recordSuccess() {
        success.increment();
    }

    public void recordFailure() {
        fail.increment();
    }

    public int getConcurrency() {
        adjustIfNeeded();
        return current.get();
    }

    private void adjustIfNeeded() {
        long now = System.currentTimeMillis();
        if (now - lastAdjustTime < ADJUST_INTERVAL_MS) {
            return; // 时间未到
        }
        lastAdjustTime = now;

        long succ = success.sum();
        long faild = fail.sum();
        long total = succ + faild;

        if (total == 0) return;

        double failRate = faild * 1.0 / total;

        if (failRate >= 0.10 && current.get() > MIN_CONCURRENCY) {
            current.set(MIN_CONCURRENCY);
            log.warn("⚠️ 上传失败率高 ({})，自动降级并发为 {}", failRate, MIN_CONCURRENCY);
        } else if (failRate < 0.05 && current.get() < MAX_CONCURRENCY) {
            current.set(MAX_CONCURRENCY);
            log.info("✅ 上传成功率正常 ({})，自动提升并发为 {}", (1 - failRate), MAX_CONCURRENCY);
        }

        // 每次调节后清空统计数据
        success.reset();
        fail.reset();
    }
}
